class BlogsController < ApplicationController
  before_action :auth_user, except: [:index, :show]

  def new
    @blog = Blog.new
  end

  def index
    @blogs = Blog.all.order("id desc").where(is_public: true).includes(:tags, :user)
  end

  def create
    @blog = Blog.new user_attrs
    # @blog.user_id = current_user.id
    @blog.user = current_user

    if @blog.save
      flash[:notice] = '博客创建成功'
      redirect_to blogs_path
    else
      flash[:notice] = '博客创建失败'
      render :new
    end
  end

  def show
    @blog = Blog.find(params[:id])
  end

  def destroy
    @blog = Blog.find(params[:id])
    @blog.destroy

    flash[:notice] = '删除成功'
    redirect_to blogs_path
  end

  private
  def user_attrs
    params.require(:blog).permit(:title, :content, :is_public, :tags_string)
  end
end
